//
//  YMCountDown.m
//  JP
//
//     on 2018/6/12.
//   . All rights reserved.
//

#import "YMCountDown.h"

@implementation YMCountDown

-  (instancetype)init
{
    self = [super init];
    if (self){
        _interval = 1;
        _duration = 60;
    }
    return self;
}
- (void)dealloc
{
    [self deallocTimer];
}
- (void)deallocTimer
{
    if (_timer){
        [_timer invalidate];
        _timer = nil;
    }
    self.running = NO;
}
- (void)fire
{
    [self deallocTimer];
    if ([self.delegate respondsToSelector:@selector(countDownWillFire:)]){
        [self.delegate countDownWillFire:self];
    }
    self.running = YES;
    if ([self.delegate respondsToSelector:@selector(countDown:runningTime:)]){
        [self.delegate countDown:self runningTime:_duration];
    }
    
    if (_duration < _interval){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.running = NO;
            if ([self.delegate respondsToSelector:@selector(countDown:didStopInTime:)]){
                [self.delegate countDown:self didStopInTime:0];
            }
        });
        return;
    }

    __block NSTimeInterval current = _duration;
    NSTimeInterval interval = _interval;
    __weak typeof(self) self_weak = self;
    _timer = [NSTimer timerWithTimeInterval:_interval block:^(NSTimer * _Nonnull timer) {
        if (self_weak == nil) return ;
        
        current -= interval;
        if (current <= 0){
            [self_weak deallocTimer];
            if ([self_weak.delegate respondsToSelector:@selector(countDown:didStopInTime:)]){
                [self_weak.delegate countDown:self_weak didStopInTime:current];
            }
        }else{
            if ([self_weak.delegate respondsToSelector:@selector(countDown:runningTime:)]){
                [self_weak.delegate countDown:self_weak runningTime:current];
            }
        }

    } repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)stop
{
    [self deallocTimer];
    if ([self.delegate respondsToSelector:@selector(countDown:didStopInTime:)]){
        [self.delegate countDown:self didStopInTime:0];
    }
}

@end
